package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_report

import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.interstitial.api.ATInterstitial
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.nativead.api.ATNativePrepareExInfo
import com.anythink.nativead.api.ATNativePrepareInfo
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.rewarded_ad.AdMobRewardedAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.rewarded_ad.AdMobRewardedAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.listener.manual_load.TopOnInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.SelfRenderViewUtil
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.rewarded_ad.TopOnRewardVideoAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.rewarded_ad.manual_load.TopOnRewardVideoAdListener
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_bloodpressure.BloodPressureData
import com.bp.hearthealth.pulse.lnapps.bp_extension.BpGlobalUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.BpBloodPressureViewModel
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_view.BloodPressureViewActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.BpDeleteDialog
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.throttleClick
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityBloodPressureResultBgBinding
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.hjq.toast.Toaster
import org.koin.androidx.viewmodel.ext.android.viewModel

class BloodPressureResultActivity : BpBaseActivity<ActivityBloodPressureResultBgBinding>() {

    private var fromType: String = ""
    private var nativeAd: NativeAd? = null
    private val viewModel: BpBloodPressureViewModel by viewModel()
    private var currentBloodPressureData: BloodPressureData? = null
    private var type = ""
    private var bpdId = ""
    private var date = 0L
    private lateinit var deleteDialog: BpDeleteDialog
    private var topOnNativeAd: com.anythink.nativead.api.NativeAd? = null

    override fun initData() {
        super.initData()
//        AdMobRewardedAdManager.loadRewardedAd(Constants.Rewarded)
        if (!AdsSwitch.getBoolean(AdsSwitch.adInterCacheControl)) {
            TopOnInterAdManager.initManualLoadInterstitialAd(this)
            TopOnInterAdManager.manualLoadAd()
        }
        loadTopOnRewardVideoAd()
        registerObserver()
        binding.viewModel = viewModel
        setViewContent()

        bpdId = intent.getStringExtra("bpdId").toString()
        LogUtil.i("详情id：$bpdId")
        date = intent.getLongExtra("date", 0)
        type = intent.getStringExtra("type").toString()
        viewModel.getBloodPressureDataByPid(bpdId)

        fromType = when (type) {
            Constants.BLOOD_PRESSURE_RECORD -> Constants.BLOOD_PRESSURE_RESULT_VIEW
            else -> Constants.BLOOD_PRESSURE_LIST_RESULT_VIEW
        }
    }

    private fun registerObserver() {
        viewModel.timerDown.observe(this) {
            if (it) {
//                loadRewardedVideoAds()
                showRewardVideoAd()
            }
        }
        viewModel.deleteResult.observe(this, Observer { result ->
            val code = result.getOrNull()
            if (code == null) {
                Toaster.show(result.exceptionOrNull())
                result.exceptionOrNull()?.printStackTrace()
                return@Observer
            }
            if (code > 0) {
                BpLiveDataBus.with<Boolean>(Constants.REFRESH_TRACKER).postData(true)
                LogUtil.e("删除成功")
                if (this::deleteDialog.isInitialized) {
                    deleteDialog.dismiss()
                    finish()
                }
            }
        })
        viewModel.unlockResult.observe(this, Observer { result ->
            val response = result.getOrNull()
            if (response == null) {
                Toaster.show(result.exceptionOrNull())
                result.exceptionOrNull()?.printStackTrace()
                return@Observer
            }
            if (response > 0) {
                LogUtil.i("解锁成功")
                viewModel.unLocked.set(true)
                BpGlobalUtil.setTextLayoutParams(binding.tvUnlocked, 8f)
            }
        })
        viewModel.bloodPressureDataInfo.observe(this, Observer { result ->
            if (result == null) {
                Toaster.show("null")
                return@Observer
            }
            LogUtil.i("详情数据：$result")
            currentBloodPressureData = result
            binding.bean = result
            if (result.unlocked) {
                BpGlobalUtil.setTextLayoutParams(binding.tvUnlocked, 8f)
            } else {
                viewModel.startTimer()
            }
        })
    }


    override fun onPause() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onPause()
        }
        super.onPause()
        viewModel.stopTimer()
    }

    override fun onResume() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onResume()
        }
        super.onResume()
    }



    private fun loadTopOnNativeAd() {
        if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
            setNativeTopOnAdView()
        } else {
            TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener{
                override fun onNativeAdLoaded() {
                    LogUtil.iTopOn("TopOn 【原生广告】 监听，显示广告")
                    if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
                        setNativeTopOnAdView()
                    }
                }
            })
        }
    }

    private fun setNativeTopOnAdView() {
        topOnNativeAd = TopOnNativeAdManager.getNativeAds().first()
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdImpressed(view: ATNativeAdView, entity: ATAdInfo) {
                //原生广告埋点
                if (type == Constants.BLOOD_PRESSURE_RECORD) {
                    //点击返回入口后_插页广告
                    AppsFlyerUtils.trackEvent("ad_native_bp_result_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f664720c8bbb27")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Blood Pressure Result页_原生广告】")
                } else {
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f664720e219e40")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压 History-Result页_原生广告】")
                    AppsFlyerUtils.trackEvent("ad_native_bp_history_result_show")
                }
                TopOnNativeAdManager.removeUsedNativeAdListener()
            }
        })
        binding.nativeAdView.removeAllViews()
        var mNativePrepareInfo: ATNativePrepareInfo? = null
        try {
            mNativePrepareInfo = ATNativePrepareExInfo()
            if (topOnNativeAd?.isNativeExpress == true) {
                LogUtil.iTopOn("【原生广告】 自渲染广告")
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    null
                )
            } else {
                LogUtil.iTopOn("【原生广告】 模板广告")
                SelfRenderViewUtil.bindSelfRenderView(
                    activity,
                    topOnNativeAd?.adMaterial,
                    binding.nativeSelfrenderView.root,
                    mNativePrepareInfo
                )
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    binding.nativeSelfrenderView.root
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        topOnNativeAd?.prepare(binding.nativeAdView, mNativePrepareInfo)
        binding.nativeAdView.visibility = View.VISIBLE
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdCloseButtonClick(view: ATNativeAdView, entity: ATAdInfo) {
                TopOnNativeAdManager.destroyAd()
                binding.nativeAdView.visibility = View.GONE
            }
        })
    }


    private fun setViewContent() {
        if (AdsSwitch.getBoolean(AdsSwitch.adNativeBPResult)) {
//            loadAdMobNativeAd()
            loadTopOnNativeAd()
        }
        binding.includeArticle.apply {
            firstText = UIHelperBp.getString(R.string._healthy_diet_tips_1_str)
            secondText = UIHelperBp.getString(R.string._healthy_diet_tips_6_str)
            thirdText = UIHelperBp.getString(R.string._healthy_diet_tips_2_str)
        }
    }

    override fun initListener() {
        super.initListener()
        binding.apply {
            tvCancel.throttleClick {
                this@BloodPressureResultActivity.viewModel.showViewToUnlock.set(true)
                this@BloodPressureResultActivity.viewModel.countDownTimer?.cancel()
            }
            tvViewToUnlock.throttleClick {
                if (TopOnRewardVideoAdManager.isAdReady()) {
                    TopOnRewardVideoAdManager.mRewardVideoAd!!.show(this@BloodPressureResultActivity)
                } else {
//                需要处理多次点击加载广告
                    Toaster.show(UIHelperBp.getString(R.string._no_ads_hint_str))
                }
            }
            includeArticle.apply {
                ivArticleFirst.throttleClick {
                    startArticleActivity(
                        binding.includeArticle.firstText.toString(),
                        R.mipmap.hd_1,
                        fromType
                    )
                }
                ivArticleSecond.throttleClick {
                    startArticleActivity(
                        binding.includeArticle.secondText.toString(),
                        R.mipmap.hd_2,
                        fromType
                    )
                }
                ivArticleThird.throttleClick {
                    startArticleActivity(
                        binding.includeArticle.thirdText.toString(),
                        R.mipmap.hd_3,
                        fromType
                    )
                }
            }
        }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        binding.includeReport.apply {
            ImmersionBar.with(this@BloodPressureResultActivity).titleBar(toolbar).init()
            tvBack.text = UIHelperBp.getString(R.string._result_str)
            tvBack.setOnClickListener {
                loadTopOnInsertAd()
//                loadAdMobInsertAd()
            }
            if (type == Constants.BLOOD_PRESSURE_RECORD) {
                tvRight.throttleClick {
                    //需要显示广告
                    startActivity(Intent(activity, BloodPressureViewActivity::class.java))
                    finish()
                }
                tvRight.text = getString(R.string._done_str)
                tvRight.setTextColor(UIHelperBp.getColor(R.color.color_027FFB))
                //血压结果页展示
                AppsFlyerUtils.trackEvent("bp_result_show")
            } else /*if (type == Constants.BLOOD_PRESSURE_LIST) */ {
                //血压列表结果页展示
                AppsFlyerUtils.trackEvent("bp_history_result_show")
                tvRight.text = getString(R.string._delete_str)
                tvRight.throttleClick {
                    deleteDialog = BpDeleteDialog(activity!!)
                    deleteDialog.showDialog()
                    deleteDialog.setOnBtnClickLisener(object : BpDeleteDialog.OnBtnClickListener {
                        override fun onBtnClick() {
                            viewModel.delete(Constants.USER_ID, date, bpdId)
                        }
                    })
                }
            }
        }
    }

    private fun loadTopOnRewardVideoAd() {
        TopOnRewardVideoAdManager.initManualLoadRewardVideoAd()
        TopOnRewardVideoAdManager.setManualLoadListener(object : TopOnRewardVideoAdListener {
            override fun onFireBaseAdIsClosed() {
                super.onFireBaseAdIsClosed()
            }

            override fun onRewardedVideoAdClosed(entity: ATAdInfo) {
                TopOnRewardVideoAdManager.releaseManualLoadRewardVideoAd()
                viewModel.unlock(bpdId)
            }

            override fun onRewardedVideoAdPlayStart(entity: ATAdInfo) {
                if (type == Constants.BLOOD_PRESSURE_RECORD) {
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_REWARDED_ID,"f66472131881c9")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压 History-Result页_激励广告】")
                } else{
                    //血压列表结果页展示
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_REWARDED_ID,"f6647211877ff3")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Blood Pressure Result页_激励广告】")
                }
            }
        })
        TopOnRewardVideoAdManager.manualLoadAd()
    }

    private fun showRewardVideoAd() {
        if (TopOnRewardVideoAdManager.isAdReady()) {
            TopOnRewardVideoAdManager.mRewardVideoAd!!.show(this@BloodPressureResultActivity)

        } else {
            Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
        }
    }

    /**
     *  激励视频广告
     *
     *  ■ 默认5s倒计时结束时，自动触发 View to Unlock 按钮，展示激励视频广告
     *     ● 激励视频广告资源加载到，立即展示，广告关闭后自动解锁 Exclusive Advice内容
     *     ● 激励广告资源未加载到，展示提示"Unlock failed, please check your netweork and retry."并展示View to Unlock按钮
     */
    private fun loadRewardedVideoAds() {
        viewModel.stopTimer()
        if (AdMobRewardedAdManager.getRewardedAd() == null) {
            //激励未加载到时加载插页
//            loadAdMobInsertAd(true)
            loadTopOnInsertAd(true)
//            Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
        } else {
            AdMobRewardedAdManager.setRewardedAdListener(object : AdMobRewardedAdListener {
                override fun onAdDismissedFullScreenContent() {
                    AdMobRewardedAdManager.release()
                    viewModel.unlock(bpdId)
                }

                override fun onAdShowedFullScreenContent() {
                    AppsFlyerUtils.trackEvent("ad_rv_bp_result_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_REWARDED_ID,"f66472131881c9")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压 History-Result页_激励广告】")
                }

                override fun onAdFailedToShowFullScreenContent() {
//                    loadAdMobInsertAd(true)
                    loadTopOnInsertAd(true)
//                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                }

                override fun onAdClosed() {
                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                }
            })
            AdMobRewardedAdManager.showRewardedAd(this)
        }
    }


    /**
     * 插页广告
     *
     *  ○ 点击back入口，展示插页广告，该条检测数据保存
     *     ■ 插页广告资源加载到，立即展示，广告关闭后自动跳转至上一级页面
     *     ■ 插页广告资源未加载到，自动跳转至上一级页面
     */
    private fun loadAdMobInsertAd(vararg rewardAd: Boolean) {
        AdMobInterstitialAdManager.setInterstitialAdListener(object : AdMobInterstitialAdListener {
            override fun onAdDismissedFullScreenContent() {
                if (rewardAd.isNotEmpty()) {
                    viewModel.unlock(bpdId)
                } else {
                    finish()
                }
            }

            override fun onAdFailedToShowFullScreenContent() {
                if (rewardAd.isNotEmpty()) {
                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                } else {
                    finish()
                }
            }

            override fun onNotReady() {
                if (rewardAd.isNotEmpty()) {
                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                } else {
                    finish()
                }
            }

            override fun onAdShowedFullScreenContent() {
                if (rewardAd.isNotEmpty()) {
                    if (type == Constants.BLOOD_PRESSURE_RECORD) {
                        //血压结果页  激励展示失败-插页展示
                        AppsFlyerUtils.trackEvent("ad_inter_bp_result_rv_show")
                    } else {
                        //血压History-Result页 激励展示失败-插页展示
                        AppsFlyerUtils.trackEvent("ad_inter_bp_history_result_rv_show")
                    }
                } else {
                    if (type == Constants.BLOOD_PRESSURE_RECORD) {
                        //点击返回入口后_插页广告
                        AppsFlyerUtils.trackEvent("ad_inter_bp_result_back_show")
                        ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID,"f66471f94edd80")
                        LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压结果页点击返回入口后_插页广告】")
                    } else {
                        ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID,"f66471fb70050e")
                        LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压History结果页点击返回入口后_插页广告】")
                        AppsFlyerUtils.trackEvent("ad_inter_bp_history_result_back_show")
                    }
                }
            }
        })
        AdMobInterstitialAdManager.showInterstitialAd(this)
    }

    private fun loadTopOnInsertAd(vararg rewardAd: Boolean) {
        topOnNativeAd?.let { TopOnNativeAdManager.removeUsedNativeAd(it) }
        TopOnInterAdManager.setManualLoadListener(object : TopOnInterstitialAdListener {
            override fun onInterstitialAdShow(entity: ATAdInfo) {
                if (rewardAd.isNotEmpty()) {
                    if (type == Constants.BLOOD_PRESSURE_RECORD) {
                        //血压结果页  激励展示失败-插页展示
                        AppsFlyerUtils.trackEvent("ad_inter_bp_result_rv_show")
                    } else {
                        //血压History-Result页 激励展示失败-插页展示
                        AppsFlyerUtils.trackEvent("ad_inter_bp_history_result_rv_show")
                    }
                } else {
                    if (type == Constants.BLOOD_PRESSURE_RECORD) {
                        //点击返回入口后_插页广告
                        AppsFlyerUtils.trackEvent("ad_inter_bp_result_back_show")
                        ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID,"f66471f94edd80")
                        LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压结果页点击返回入口后_插页广告】")
                    } else {
                        ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID,"f66471fb70050e")
                        LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压History结果页点击返回入口后_插页广告】")
                        AppsFlyerUtils.trackEvent("ad_inter_bp_history_result_back_show")
                    }
                }
            }

            override fun onFireBaseAdIsClosed() {
                if (rewardAd.isNotEmpty()) {
                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                } else {
                    finish()
                }
            }

//            override fun onInterstitialAdLoaded() {
//                LogUtil.iTopOn("插页广告 onInterstitialAdLoaded 回调")
//                if (TopOnInterAdManager.isAdReady()) {
//                    TopOnInterAdManager.mInterstitialAd!!.show(this@BloodPressureResultActivity)
//                } else {
//                    if (rewardAd.isNotEmpty()) {
//                        Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
//                    } else {
//                        finish()
//                    }
//                }
//            }

            override fun onInterstitialAdClose(entity: ATAdInfo) {
                if (rewardAd.isNotEmpty()) {
                    viewModel.unlock(bpdId)
                } else {
                    finish()
                }
            }

            override fun onInterstitialAdLoadFail(adError: AdError) {
                if (rewardAd.isNotEmpty()) {
                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                } else {
                    finish()
                }
            }

            override fun onInterstitialAdVideoError(adError: AdError) {
                if (rewardAd.isNotEmpty()) {
                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                } else {
                    finish()
                }
            }

            override fun onNotReady() {
                if (rewardAd.isNotEmpty()) {
                    Toaster.show(UIHelperBp.getString(R.string._rewarded_ad_not_load_str))
                } else {
                    finish()
                }
            }
        })
        TopOnInterAdManager.showInterstitialAd(this)
    }

    /**
     * 原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadAdMobNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                if (type == Constants.BLOOD_PRESSURE_RECORD) {
                    //点击返回入口后_插页广告
                    AppsFlyerUtils.trackEvent("ad_native_bp_result_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f664720c8bbb27")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Blood Pressure Result页_原生广告】")
                } else {
                    AppsFlyerUtils.trackEvent("ad_native_bp_history_result_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f664720e219e40")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【血压 History-Result页_原生广告】")
                }
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        loadTopOnInsertAd()
//        loadAdMobInsertAd()
    }

    override fun onDestroy() {
        super.onDestroy()
        //激励广告重试成功后为展示手动销毁
        TopOnInterAdManager.setManualLoadListener(null)
        AdMobRewardedAdManager.release()
        AdMobInterstitialAdManager.setInterstitialAdListener(null)
        nativeAd?.let { AdMobNativeAdManager.removeUsedNativeAd(it) }
    }
}